<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="title" label="商品名称" required>
				<uni-easyinput v-model="formData.title" />
			</uni-forms-item>
			<uni-forms-item name="src" label="封面图">
				<cloud-image name="src" v-model="formData.src" :value="formData.src" />
			</uni-forms-item>
			<uni-forms-item name="banner" label="横图">
				<cloud-image name="banner" v-model="formData.banner" imageClass="banner" :value="formData.banner" />
			</uni-forms-item>
			<uni-forms-item name="imgs" label="轮播图">
				<cloud-image name="imgs" v-model="formData.imgs" :imageNumber="8" :value="formData.imgs" />
			</uni-forms-item>

			<uni-forms-item name="subTitle" label="子标题">
				<uni-easyinput v-model="formData.subTitle" />
			</uni-forms-item>
			<uni-forms-item name="price" label="销售价格" required>
				<uni-easyinput type="number" v-model="formData.price" />
			</uni-forms-item>
			<uni-forms-item name="originPrice" label="原价">
				<uni-easyinput type="number" v-model="formData.originPrice" />
			</uni-forms-item>
			<uni-forms-item name="monthlySale" label="月售量">
				<uni-easyinput type="number" v-model="formData.monthlySale" />
			</uni-forms-item>
			<uni-forms-item name="shopid" label="店铺" required>
				<uni-data-checkbox v-model="formData.shopid" collection="cloud_shops" field="name as text, id as value" />
			</uni-forms-item>
			<uni-forms-item name="stock" label="剩余库存" required>
				<uni-easyinput type="number" v-model="formData.stock" />
			</uni-forms-item>
			<uni-forms-item name="visite" label="浏览量">
				<uni-easyinput type="number" v-model="formData.visite" />
			</uni-forms-item>
			<uni-forms-item name="limit" label="限购数量">
				<uni-easyinput placeholder="0不限制" type="number" v-model="formData.limit" />
			</uni-forms-item>
			<uni-forms-item name="isSold" label="是否销售">
				<uni-data-checkbox v-model="formData.isSold" :localdata="formOptions.isSold_localdata" />
			</uni-forms-item>
			<uni-forms-item name="isLimit" label="是否限购">
				<switch @change="binddata('isLimit', $event.detail.value)" :checked="formData.isLimit" />
			</uni-forms-item>
			<uni-forms-item name="isNewUser" label="是否新用户">
				<switch @change="binddata('isNewUser', $event.detail.value)" :checked="formData.isNewUser" />
			</uni-forms-item>
			<uni-forms-item name="isRecommend" label="是否推荐">
				<switch @change="binddata('isRecommend', $event.detail.value)" :checked="formData.isRecommend" />
			</uni-forms-item>
			<uni-forms-item name="posid" label="排序">
				<uni-easyinput type="number" v-model="formData.posid" />
			</uni-forms-item>
			<uni-forms-item name="onlySelfTake" label="仅自提">
				<uni-data-checkbox v-model="formData.onlySelfTake" :localdata="formOptions.onlySelfTake_localdata" />
			</uni-forms-item>
			<uni-forms-item name="saleType" label="销售类型">
				<uni-data-checkbox v-model="formData.saleType" :localdata="formOptions.saleType_localdata" />
			</uni-forms-item>
			<uni-forms-item name="score" label="评分">
				<uni-easyinput placeholder="商品评分，1-10" type="number" v-model="formData.score" />
			</uni-forms-item>
			<uni-forms-item name="share" label="分享词">
				<uni-easyinput v-model="formData.share" />
			</uni-forms-item>
			<uni-forms-item name="specsType" label="规格类型">
				<uni-data-checkbox v-model="formData.specsType" :localdata="formOptions.specsType_localdata" />
			</uni-forms-item>
			<block v-if="formData.specsType=='multiple'">
				<uni-forms-item name="skuname" label="规格名称">
					<uni-data-checkbox v-model="formData.skuname" :localdata="formOptions.skuname_localdata" :multiple="true" @change="changeSkuName" />
				</uni-forms-item>
				<view v-for="(item,index) in skuOriginList" :key="index" class="margin-bottom-sm">
					<text>{{index}}</text>
					<view v-for="(item2,index2) in item" :key="index2" class="margin-bottom-sm flex align-center">
						<text>名称：</text>
						<uni-easyinput :placeholder="'请输入'+index+(index2+1)" v-model="item2.value" />
						<text class="margin-left-sm">库存：</text>
						<uni-easyinput :placeholder="'请输入'+index+(index2+1)+'库存'" v-model="item2.amount" />
						<uni-icons v-if="index2== item.length -1 " class="margin-left-sm" type="plusempty" @click="addSku(index,index2)"></uni-icons>
						<uni-icons v-else class="margin-left-sm" type="closeempty" @click="delSku(index,index2)"></uni-icons>
					</view>
				</view>
				<uni-forms-item name="skus" label="">
					<view v-for="(item,index) in formData.skus" :key="index" class="">
						<uni-forms :ref="'form'+index" :value="item" validateTrigger="bind">
							<uni-forms-item name="name" label="名称" labelWidth="50" labelAlign="right">
								<uni-easyinput name="name" v-model="item.name" :disabled="true" />
							</uni-forms-item>
							<view class="flex align-center">
								<uni-forms-item name="price" label="价格" labelWidth="50" labelAlign="right">
									<uni-easyinput placeholder="请输入价格" type="digit" name="price" v-model="item.price" />
								</uni-forms-item>
								<uni-forms-item name="stock" label="库存" labelWidth="50" labelAlign="right">
									<uni-easyinput placeholder="请输入库存" type="number" name="stock" v-model="item.stock" />
								</uni-forms-item>
							</view>
						</uni-forms>
					</view>
				</uni-forms-item>
			</block>
			<uni-forms-item name="storage_condition" label="储存条件">
				<uni-easyinput v-model="formData.storage_condition" />
			</uni-forms-item>
			<uni-forms-item name="net_weight" label="净重">
				<uni-easyinput v-model="formData.net_weight" />
			</uni-forms-item>
			<uni-forms-item name="manufacture" label="生成日期">
				<uni-easyinput v-model="formData.manufacture" />
			</uni-forms-item>
			<uni-forms-item name="guarantee_period" label="保质期">
				<uni-easyinput v-model="formData.guarantee_period" />
			</uni-forms-item>
			<uni-forms-item name="upc" label="条码">
				<uni-easyinput v-model="formData.upc" />
			</uni-forms-item>

			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator,
		enumConverter
	} from '../../js_sdk/validator/cloud_goods.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'cloud_goods';

	function getValidator(fields) {
		let reuslt = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				reuslt[key] = validator[key]
			}
		}
		return reuslt
	}

	export default {
		data() {
			return {
				timerId: null,
				skuOriginList: {},
				formData: {
					"id": null,
					"src": "",
					"banner": "",
					"title": "",
					"subTitle": "",
					"price": 0,
					"originPrice": 0,
					"monthlySale": 0,
					"shopid": null,
					"stock": 100,
					"visite": 0,
					"limit": 0,
					"isSold": 0,
					"isLimit": false,
					"isNewUser": false,
					"isRecommend": false,
					"posid": 0,
					"onlySelfTake": 0,
					"saleType": "normal",
					"score": 10,
					"share": "",
					"skus": [],
					"specsType": "single",
					"storage_condition": "",
					"net_weight": "",
					"manufacture": "",
					"guarantee_period": "",
					"tuangou": null,
					"upc": "",
					"imgs": []
				},
				formOptions: {
					"isSold_localdata": [{
							"text": "下架",
							"value": 0
						},
						{
							"text": "在售",
							"value": 1
						}
					],
					"isLimit_localdata": [{
							"text": "否",
							"value": false
						},
						{
							"text": "是",
							"value": true
						}
					],
					"isRecommend_localdata": [{
							"text": "否",
							"value": false
						},
						{
							"text": "是",
							"value": true
						}
					],
					"onlySelfTake_localdata": [{
							"text": "否",
							"value": 0
						},
						{
							"text": "是",
							"value": 1
						}
					],
					"saleType_localdata": [{
							"text": "正常销售",
							"value": "normal"
						},
						{
							"text": "提前预定",
							"value": "yuding"
						},
						{
							"text": "社区团购",
							"value": "tuangou"
						}
					],
					"specsType_localdata": [{
							"text": "单规格",
							"value": "single"
						},
						{
							"text": "多规格",
							"value": "multiple"
						}
					],
					"skuname_localdata": []
				},
				rules: {
					...getValidator(["id", "src", "banner", "title", "subTitle", "price", "originPrice", "monthlySale", "stock",
						"visite", "limit", "isSold", "isLimit", "isNewUser", "isRecommend", "posid", "onlySelfTake", "saleType", "score",
						"share", "skus", "specsType", "storage_condition", "net_weight", "manufacture", "guarantee_period", "tuangou",
						"upc", "imgs", "shopid", "skuname"
					])
				}
			}
		},
		watch: {
			skuOriginList: {
				handler(newVal) {
					if (this.timerId) {
						clearTimeout(this.timerId);
					}
					this.timerId = setTimeout(() => {
						let skus = []
						let id = 10000;
						let exts = [];
						for (let key in newVal) {
							exts.push(key);
							for (let f1 of newVal[key]) {
								for (let key1 in newVal) {
									if (exts.indexOf(key1) == -1) {
										for (let f2 of newVal[key1]) {
											if (f1.value && f2.value) {
												skus.push({
													"id": id,
													"name": [f1.value, f2.value].join("&gt;"),
													"price": 0,
													"stock": f1.amount * 1 + f2.amount * 1
												})
												id++;
												console.log(f1.value + "-" + f2.value)
											}
										}
									}
								}
							}
						}
						//只有一个规格
						if (exts.length == 1 && skus.length == 0) {
							for (let key in newVal) {
								exts.push(key);
								for (let f1 of newVal[key]) {
									if (f1.value) {
										skus.push({
											"id": id,
											"name": f1.value,
											"price": 0,
											"stock": f1.amount * 1
										})
										id++;
									}
								}
							}
						}
						for (let s of this.formData.skus) {

						}
						//与原来的sku做比较
						this.$set(this.formData, "skus", skus)
					}, 1000)
				},
				deep: true
			}
		},
		onReady() {
			this.getSkuNames();
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					this.submitForm(res)
				}).catch((errors) => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				// 使用 clientDB 提交数据
				db.action("genId").collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getSkuNames() {
				for (let name of enumConverter.skunames) {
					this.formOptions.skuname_localdata.push({
						"text": name,
						"value": name
					})
				}
			},
			changeSkuName(e) {
				//隐藏不存在的
				for (let key in this.skuOriginList) {
					if (e.detail.value.indexOf(key) == -1) {
						delete this.skuOriginList[key]
					}
				}
				console.log("changeSkuName", e)
				for (let name of e.detail.value) {
					if (!this.skuOriginList[name]) {
						this.$set(this.skuOriginList, name, []);
						//this.skuOriginList[name] = [];
						this.skuOriginList[name].push({
							value: "",
							amount: "10",
						})
					}
				}
				//生成规格信息
				console.log(this.skuOriginList)
			},
			addSku(index, index2) {
				this.skuOriginList[index].push({
					value: "",
					amount: "10",
				})
			},
			delSku(index, index2) {
				console.log("delete", index, index2)
				this.skuOriginList[index].splice(index2, 1)
			},
			changeSku(e) {
				console.log("changeSku", e)
			}
		}
	}
</script>
